﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using Medianamik.UI.Lock;
using NLog;
using Medianamik.Core;
using Medianamik.Core.Logging;
using Medianamik.Core.Lock;

namespace Medianamik.UI.Services
{
    [WebService(Namespace = "http://absolunet.com/medianamik/webservices/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class LockWebService : System.Web.Services.WebService
    {
        private static ILogger _logger;
        protected static ILogger Logger
        {
            get
            {
                return _logger
                    ?? (_logger = new ObjectFactory<ILogger>().Get("LockWebServiceLogger"));
            }
        }

        [WebMethod]
        public int Ping(Guid pObjectId)
        {
            try
            {

                var transac = LockContext.CurrentTransaction;
                if (transac == null) { return (int)LockStatus.Elapsed; }

                return (int)transac.KeepAlive(pObjectId);

            }
            catch (Exception e)
            {
                Logger.Warn("Erreur lors du renouvellement du Lock", e);
            }

            //En cas de probleme on veut que les usagers puissent continuer à editer
            return (int)LockStatus.KeepAlive;
        }

        [WebMethod]
        public int Lock(Guid pObjectId, int pUltimatum)
        {
            try
            {
                if (LockManager.IsLocked(pObjectId))
                {
                    return (int)LockStatus.Elapsed;
                }

                Transaction t = LockContext.CurrentTransaction;
                if (t == null) { t = new Transaction(); }
                t.Lock(pObjectId, TimeSpan.FromSeconds(pUltimatum), HttpContext.Current.User.Identity.Name);

            }
            catch (Exception e)
            {
                Logger.Warn("Erreur lors de la demande de Lock", e);
                throw;
            }
            return (int)LockStatus.KeepAlive;
        }

        [WebMethod]
        public bool Unlock(Guid pObjectId)
        {
            Transaction t = LockContext.CurrentTransaction;
            t.Unlock(pObjectId);
            return true;
        }

        [WebMethod]
        public int Check(Guid pObjectId)
        {
            if (LockManager.IsLocked(pObjectId))
            {
                return 1;
            }
            return 0;
        }
    }
}
